﻿/*--------------------------------------------------------------------------------
 * Adaptive Intelligence - Foundation Framework
 * Version 2.10
 * 
 * POP3 Client Class
 *      Provides a class for connecting to and communicating with a POP3 server.
 *------------------------------------------------------------------------------*/

/*--------------------------------------------------------------------------------
 * System Imports
 *------------------------------------------------------------------------------*/
using System;
using System.Text;
using Adaptive.Foundation;
using Adaptive.Foundation.Network.Cnr;
using Adaptive.Network.Sockets;

namespace Adaptive.Foundation.Network.Pop3
{
    /// <summary>
    /// Provides a class for connecting to and communicating with a POP3 server.
    /// </summary>
    public class Pop3Client : DisposableObjectBase 
    {
        /*--------------------------------------------------------------------------------
         * Public Event Definitions
         *------------------------------------------------------------------------------*/
        #region Public Event Definitions
        /// <summary>
        /// Occurs when the user identity value is sent.
        /// </summary>
        public event CnrAuthenticationEventHandler UserIdentitySent;
        /// <summary>
        /// Occurs when the user identity value is accepted.
        /// </summary>
        public event CnrAuthenticationEventHandler UserIdentityAccepted;
        /// <summary>
        /// Occurs when the user identity value is rejected.
        /// </summary>
        public event CnrAuthenticationEventHandler UserIdentityRejected;
        /// <summary>
        /// Occurs when the security / password value is sent.
        /// </summary>
        public event CnrAuthenticationEventHandler UserPasswordSent;
        /// <summary>
        /// Occurs when the security / password value is accepted.
        /// </summary>
        public event CnrAuthenticationEventHandler UserPasswordAccepted;
        /// <summary>
        /// Occurs when the security / password value is rejected.
        /// </summary>
        public event CnrAuthenticationEventHandler UserPasswordRejected;
        /// <summary>
        /// Occurs when new credential data is required.
        /// </summary>
        public event CnrAuthenticationRequiredEventHandler QueryCredentials;
        #endregion

        /*--------------------------------------------------------------------------------
         * Private Constants Declarations
         *------------------------------------------------------------------------------*/
        #region Private Constants Declarations
        #endregion

        /*--------------------------------------------------------------------------------
         * Private Member Declarations
         *------------------------------------------------------------------------------*/
        #region Private Member Declarations

        private SocketsClient _client;
        private AuthorizationSession _authSession;
        private CnrCredentials _credentials;
        private string _buffer;

        #endregion

        /*--------------------------------------------------------------------------------
         * Constructor / Dispose / Destructor Methods
         *------------------------------------------------------------------------------*/
        #region Constructor / Dispose / Destructor Methods
        /// <summary>
        /// Initializes a new instance of the class.
        /// </summary>
        /// <remarks>
        /// This is the default constructor.
        /// </remarks>
        public Pop3Client()
            : base()
        {
            _credentials = new CnrCredentials();
        }
        /// <summary>
        /// Deallocates internally allocated objects.
        /// </summary>
        /// <param name="disposing">
        /// A value indicating whether the object is being disposed.
        /// </param>
        protected override void Dispose(bool disposing)
        {
            if ((!Disposed) && (disposing))
            {
                if (_credentials != null)
                    _credentials.Dispose();

                if (_client != null)
                    _client.Dispose();

                if (_authSession != null)
                    _authSession.Dispose();
            }

            _credentials = null;
            _client = null;
            _authSession = null;
            base.Dispose(disposing);
        }
        #endregion

        /*--------------------------------------------------------------------------------
         * Public Properties
         *------------------------------------------------------------------------------*/
        #region Public Properties
        /// <summary>
        /// Gets the reference to the credentials needed for connection.
        /// </summary>
        /// <value>
        /// A <see cref="CnrCredentials"/> instance.
        /// </value>
        public CnrCredentials Credentials
        {
            get { return _credentials; }
        }
        #endregion

        /*--------------------------------------------------------------------------------
         * Protected Methods / Event Methods
         *------------------------------------------------------------------------------*/
        #region Protected Methods / Event Methods
        #endregion

        /*--------------------------------------------------------------------------------
         * Public Methods / Functions
         *------------------------------------------------------------------------------*/
        #region Public Methods / Functions]
        /// <summary>
        /// Attempts to open a connection to the specified POP3 Server.
        /// </summary>
        /// <param name="mailServerName">
        /// The domain name or address of the server to populate.
        /// </param>
        public bool StandardConnect(String mailServerName)
        {
            bool returnValue = false;               //Return value.
            QuitCommand quitCommand = null;         //Command for terminating session.

            if (_client != null)
                Disconnect();

            _client = new SocketsClient();
            _buffer = string.Empty;

            if (_client.Connect(mailServerName, 110))
            {
                //Wait for connection.
                _buffer = _client.WaitForStringData("\r\n", 10);

                _authSession = new AuthorizationSession(_client);
                _authSession.Credentials.UserIdentityValue = _credentials.UserIdentityValue;
                _authSession.Credentials.SecurityValue = _credentials.SecurityValue;
                _authSession.QueryCredentials += new CnrAuthenticationRequiredEventHandler(HandleCredentialsQuery);

                returnValue = _authSession.ExecuteAuthentication();
                if (!returnValue)
                {
                    //Exit the protocol on authentication failure.
                    quitCommand = new QuitCommand(_client);
                    quitCommand.Execute();

                    //Close the connection.
                    _authSession.Dispose();
                    _authSession = null;
                    _client.Close();
                    _client.Dispose();
                    _client = null;
                }
            }
            else
            {
                _client.Dispose();
                _client = null;
            }
            return returnValue;
        }

        void HandleClientDataRecieved(object sender, DataReceivedEventArgs e)
        {
            _buffer += e.DataRecieved;
        }
        /// <summary>
        /// Disconnects from a remote POP3 Server, if currently connected.
        /// </summary>
        public void Disconnect()
        {
            QuitCommand quitCommand = null;         //Command for terminating session.

            if (_client != null)
            {
                //Exit the protocol on authentication failure.
                quitCommand = new QuitCommand(_client);
                quitCommand.Execute();

                //Close the connection.
                _authSession.Dispose();
                _authSession = null;
                _client.Close();
                _client.Dispose();
                _client = null;
            }
        }
        /// <summary>
        /// Gets the number of messages in the current inbox.
        /// </summary>
        /// <returns>
        /// The number of messages waiting to be downloaded.
        /// </returns>
        public int GetMailCount()
        {
            StatCommand command = null;             //Command to send.
            Pop3Response response = null;           //Response to parse.
            string[] dataItems = null;              //Data container.

            int returnValue = 0;

            if (_client != null)
            {
                command = new StatCommand(_client);
                response = (Pop3Response)command.Execute();

                if (response.Success)
                {
                    dataItems = response.ResponseData.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
                    if ((dataItems != null) && (dataItems.Length > 0))
                    {
                        returnValue = Convert.ToInt32(dataItems[0]);
                    }
                }
                else
                    returnValue = -1;

                response.Dispose();
                command.Dispose();
            }

            return returnValue;
        }
        #endregion

        /*--------------------------------------------------------------------------------
         * Private Event Handlers
         *------------------------------------------------------------------------------*/
        #region Private Event Handlers
        /// <summary>
        /// Handles the event when the authentication session requests new credentials.
        /// </summary>
        /// <param name="sender">The object raising the event.</param>
        /// <param name="e">
        /// A <see cref="CnrAuthenticationRequiredEventArgs"/> event arguments instance containing
        /// the parameters.
        /// </param>
        private void HandleCredentialsQuery(object sender, CnrAuthenticationRequiredEventArgs e)
        {
            if (QueryCredentials == null)
            {
                e.Cancel = true;
            }
            else
            {
                QueryCredentials(this, e);
            }
        }
        #endregion

        /*--------------------------------------------------------------------------------
         * Private Methods / Functions
         *------------------------------------------------------------------------------*/
        #region Private Methods / Functions
        #endregion
    }
}
